#!/usr/bin/env python
#
#

__copyright__ = 'this file is in the public domain'
__revision__ = '$Id: runbot 379 2006-03-14 13:22:58Z bart $'

import sys, os
vi = sys.version_info

if vi[0] < 2 or (vi[0] == 2 and vi[1] < 4):
     print "i need at least python version >= 2.4"
     os._exit(1)

sys.setcheckinterval(100)
from gozerbot.generic import rlog, handle_exception, die
from gozerbot.config import config

try:
    from gozerbot.jabberbot import Bot
    rlog(10,'PYJBOT','starting %s' % config['version'])
    from gozerbot.fleet import fleet
    from gozerbot.plugins import plugins
    from gozerbot.backup import backup, backupstop
    import gozerbot.thr as thr
except Exception, ex:
    handle_exception()
    os._exit(1)
    
import sys, signal, time

for i in sys.argv:
    if os.path.isdir(i):
        os.chdir(i)

# write pid to pidfile
k = open('pyjbot.pid','w')
k.write(str(os.getpid()))
k.close()

# stop function
def stop(x, y):
    try:
        stopsave = 0
        backupstop = 1
        plugins.save()
        fleet.exitall()
        while saving:
            if stopsave:
                break
            rlog(10, 'world', 'waiting for %s' % str(saving))
            time.sleep(5)
            if not saving:
                time.sleep(5)
        rlog(10, 'PYJBOT', 'all saved')
    finally:
        time.sleep(2)
        die()

def reloadconfig(x, y):
    try:
        gozerbot.config.configload()
        rlog(10, 'PYJBOT', 'config reloaded')
    except Exception, ex:
        handle_exception()
        rlog(10, 'PYJBOT', 'config reload failed')
    
# register SIGTERM handler to stop
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGHUP, reloadconfig)

# startup backup thread
thr.start_new_thread(backup,())

try:
    bot = Bot(config['jabberhost'], config['jabberusername'], \
config['jabberpass'], config['jabberport'], config['jabberssl'])
    if not bot.doconnect():
        rlog(10, 'runbot', "can't login with %s" % config['jabberusername'])
        os._exit(1)
    fleet.start(bot)
    # reg plugins
    thr.start_new_thread(plugins.regplugins,())
except:
    handle_exception()
    os._exit(1)

# busy loop keeping main thread alive 
while 1:
    try:
        time.sleep(1)
    except:
        stop(0,0)
